import { PolygonGeometry, PolygonHierarchy, Cartesian3, EllipsoidSurfaceAppearance, Primitive, ScreenSpaceEventType, Cartographic,ScreenSpaceEventHandler,GeometryInstance, Material } from 'cesium';
import * as Cesium from "cesium"
import waterimg from './baseimg'
import  * as turf from "@turf/turf"
import cesiumExt from "../uitls/cesiumExt/cesiumExt"
import {get,post} from "@/ajax/http";
import './currentWater.css'
import {error} from "three";
const warningEntityId = "warningEntityborder"
const curwaterLayer = function (viewer) {
    this.viewer = viewer
    this.riverPlos = []
    this.wariningPlos = []
    this.totalArea = 0
    this.pointsCollection = null
    //二维预警指标
    this.twoIndicator = null
    this.warningLv = 0
    this.warningType = [
        "",
        new Cesium.Color(0, 0, 1, 1),
        new Cesium.Color(1, 1, 0, 1),
        new Cesium.Color(0.8, 0.8, 0.1, 1),
        new Cesium.Color(1, 0, 0, 1),
    ]
    this.warningLabel = [
        "",
        "蓝色预警",
        "黄色预警",
        "橙色预警",
        "红色预警",
    ]
    var self = this
    var handler = new ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction(function (movement) {
            var wp = movement.position;
            if (!wp) {
                return;
            }
            var ray = viewer.camera.getPickRay(wp);
            if (!ray) {
                return;
            }
            var cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            if(cartesian){
                var cartog = Cartographic.fromCartesian(cartesian);
                var lnglat = {
                    lon:cartog.longitude / Math.PI * 180,
                    lat:cartog.latitude / Math.PI * 180
                }
                self.getPicInfo(lnglat)
            }
        }, ScreenSpaceEventType.LEFT_CLICK);
}
curwaterLayer.prototype = {
    loadPolygon: function (arrayPoints, holes, height,totalArea,grids) {
        this.totalArea = totalArea || 0
        this.loadTin(grids)
        var polygon
        if (holes && holes.length > 0) {
            polygon = new PolygonGeometry({
                polygonHierarchy: new PolygonHierarchy(Cartesian3.fromDegreesArray(arrayPoints), new PolygonHierarchy(Cartesian3.fromDegreesArray(holes[0]))),
                extrudedHeight: height || 330,
                // perPositionHeight:true,
                // height:height||330,
                // vertexFormat : EllipsoidSurfaceAppearance.VERTEX_FORMAT
            });
        } else {
            polygon = new PolygonGeometry({
                polygonHierarchy: new PolygonHierarchy(Cartesian3.fromDegreesArray(arrayPoints)),
                extrudedHeight: height || 330,
                // perPositionHeight:true,
                // height:height||330,
                // vertexFormat : EllipsoidSurfaceAppearance.VERTEX_FORMAT
            });
        }
       
        var River = new Primitive({
            geometryInstances: new GeometryInstance({
                geometry: polygon
            }),
            appearance: new EllipsoidSurfaceAppearance({
                fragmentShaderSource: 'varying vec3 v_positionMC;\nvarying vec3 v_positionEC;\nvarying vec2 v_st;\nvoid main()\n{\nczm_materialInput materialInput;\nvec3 normalEC = normalize(czm_normal3D * czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)));\n#ifdef FACE_FORWARD\nnormalEC = faceforward(normalEC, vec3(0.0, 0.0, 1.0), -normalEC);\n#endif\nmaterialInput.s = v_st.s;\nmaterialInput.st = v_st;\nmaterialInput.str = vec3(v_st, 0.0);\nmaterialInput.normalEC = normalEC;\nmaterialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, materialInput.normalEC);\nvec3 positionToEyeEC = -v_positionEC;\nmaterialInput.positionToEyeEC = positionToEyeEC;\nczm_material material = czm_getMaterial(materialInput);\n#ifdef FLAT\ngl_FragColor = vec4(material.diffuse + material.emission, material.alpha);\n#else\ngl_FragColor = czm_phong(normalize(positionToEyeEC), material);\
                gl_FragColor.a=0.8;\n#endif\n}\n'
            }),
            show: true
        });
        var River1_Material = new Material({
            fabric: {
                type: 'Water',
                uniforms: {
                    baseWaterColor: {
                        alpha: 1,
                        blue: 0.28,
                        green: 0.48,
                        red:  0.63,
                        // red: 0.55,
                        // green: 0.45,
                        // blue: 0.1,
                    },
                    normalMap: waterimg,
                    // normalMap:'./demo/img/water4.png',
                    frequency: 80,          // 100
                    animationSpeed: 0.01,  //0.015
                    amplitude:15  //30
                }
            }
        });
        //展示实时淹没面积
        //预警
        this.checktwoWarning(totalArea)
        this.showArea()
        River.appearance.material = River1_Material;
        this.riverPlos.push(River)
        this.viewer.scene.primitives.add(River); //添加到场景
        //添加预警对象
        if(this.warningLv>0){
            // debugger
            // this.viewer.entities.removeById(warningEntityId)
    //         var bData = {
    //             // id:warningEntityId,
    //             polyline :{
    //                 positions: Cartesian3.fromDegreesArray(arrayPoints),
    //                 clampToGround: true,
    //                 width: new Cesium.CallbackProperty(function () {
    //                     return Math.ceil(Math.random()*10); 
    //                 }, false),
    //                 material : new Cesium.PolylineGlowMaterialProperty({
    //                      glowPower : 0.3,
    //                       color : this.warningType[this.warningLv]
    //                     
    //                  }),
    //                 show: true
    //             }
    //         }
    //         this.wariningPlos.push(bData)
    //         this.viewer.entities.add(bData); //添加到场景
        }
        
    },
    showArea(){
        var water_totalArea_dom = document.getElementById("water_totalArea")
        if(!water_totalArea_dom){
            water_totalArea_dom =  document.createElement("div");
            water_totalArea_dom.className = "cesium-info";
            water_totalArea_dom.id="water_totalArea"
            water_totalArea_dom.innerHTML = `实时淹没面积:<span>${this.totalArea}km²</span>`;
            // var body = document.getElementsByTagName("body")[0];
            // body.appendChild(dom);
            var ViewDom = this.viewer.container
            ViewDom.appendChild(water_totalArea_dom);
        }
        if(this.warningLv>0){
            water_totalArea_dom.innerHTML = `实时淹没面积:<span style="color:#f11">${this.totalArea}km²</span>
                实时预警等级:<span>${this.warningLabel[this.warningLv]}</span>`;
        }else{
            water_totalArea_dom.innerHTML = `实时淹没面积:<span style="color:#f11">${this.totalArea}km²</span>`;
        }
        
    },
    //输入二维预警指标
    InputTwoindicators(riverGridId) {
        //清除之前的指标
        get('/ews/bsEarlyWarningObject/gisList?riverGridId='+riverGridId+"&warningIndexCode=21").then((res) => {
             //插入新的二维指标
             var position = {
                    lon:res.data[0].lon,
                    lat:res.data[0].lat
             }
             var info = {
                name:"未命名"  //断面名称
             }
             var  IndexList = res.data[0].earlyWarningIndexList //断面预警指标 
             this.twoIndicator = {
                position:position,
                info:info,
                IndexList:IndexList
             }
        }).catch((err) => {
            console.log('查询二维预警指标失败')
            // message.error('查询二维预警指标失败')
        })
    },
    //判断二维网格是否报警
    checktwoWarning(tworesult){
        var warningLv = 0
        var IndexThresholdArr = []
        if(!this.twoIndicator){
            // throw new Error("没有二维预警指标")
            return
        }
          //对比实时水位和预警指标值
          if(this.twoIndicator.IndexList && this.twoIndicator.IndexList.length>0){
            this.twoIndicator.IndexList.forEach((warningTm,index) => {
                var resLv = tworesult>warningTm.warningIndexThreshold?warningTm.warningLevel:warningLv
                warningLv=warningLv>resLv?warningLv:resLv
                IndexThresholdArr.push(warningTm.warningIndexThreshold)
                if(index == this.twoIndicator.IndexList.length-1 && warningLv>0){
                    this.warningLv = warningLv
                }
            });
          }
    },
    clear() {
        this.riverPlos.forEach((poly,index)=>{
            this.viewer.scene.primitives.remove(poly)
            if(index == this.riverPlos.length-1){
                this.riverPlos= []
            }
        })
        
        this.wariningPlos.forEach((poly,index)=>{
            this.viewer.entities.remove(poly)
            if(index == this.wariningPlos.length-1){
                this.wariningPlos= []
            }
        })
        // this.wariningPlos= this.wariningPlos.splice(0,this.wariningPlos.length-1)
        // this.viewer.entities.removeById(warningEntityId)
    },
    loadTin(points){
        var turfPoins = []
        points.forEach(poi=>{
            turfPoins.push(turf.point([poi.lat, poi.lng],{ss:poi.ss,gc:poi.gc,sw:poi.sw}))
        })
        this.pointsCollection = turf.featureCollection(turfPoins);
    },
    getPicInfo(piclatlng){
        if(this.pointsCollection){
            var targetPoint = turf.point([piclatlng.lat, piclatlng.lon]);
            var nearest = turf.nearestPoint(targetPoint, this.pointsCollection);
            console.log(nearest)
            if(nearest && nearest.properties.distanceToPoint<0.002){
                this.modelClick(piclatlng,`<ul>
                <li>水深:${nearest.properties.ss}</li>
                <li>水位:${nearest.properties.sw}</li>
                <li>高程:${nearest.properties.gc}</li>
                </ul>`)
            }
        }
        
    },
    modelClick:function(latlng,content) {
        var self = this
        var position =  Cesium.Cartographic.fromDegrees(latlng.lon,latlng.lat);
        var promise = Cesium.sampleTerrain(self.viewer.terrainProvider,12,[position]);
        Cesium.when(promise, function(updatedPositions) {
             var height = updatedPositions[0].height;
            console.log(height)
             var hpoint = new Cesium.Cartesian3.fromDegrees(latlng.lon,latlng.lat,height);
             self._openinfoWindow({position:hpoint},content)
        });
    },
    _openinfoWindow:function(position,content){
        
        var self = this
        var infoTmep =  '<div class="line"></div>'+
            '<div class="main">'+
            '</div>'
        var InfoWinDom = document.getElementById("cesium-infoWindows")
        if(!InfoWinDom){
            InfoWinDom = document.createElement("div")
            InfoWinDom.innerHTML = infoTmep
            InfoWinDom.className = "ysc-dynamic-layer"
            InfoWinDom.id = "cesium-infoWindows"
            var ViewDom = self.viewer.container
            ViewDom.appendChild(InfoWinDom);
        }
        var elment = $(InfoWinDom);
        var data={
            layerId:"layer1",//英文，且唯一,内部entity会用得到
            position:position.position,
            element:elment
        };
        cesiumExt.showDynamicLayer(self.viewer,data,function (){ //回调函数 改变弹窗的内容;
            elment.find(".main").html(content);
        });
    },
    _closeinfoWindow:function(){
        var InfoWinDom = document.getElementById("cesium-infoWindows")
        if(InfoWinDom){
            $(InfoWinDom).remove()
        }
    }
}
export default curwaterLayer